import threading
import json
import time
import websocket
import logging
from tools.config_api import get_config

logger = logging.getLogger("huahua_ws_receiver")
logger.setLevel(logging.WARNING)


class HuahuaWSReceiver:
    def __init__(self, ws_url="ws://127.0.0.1:9780/app/danmu/ws", on_danmu=None):
        self.ws_url = ws_url
        self.ws = None
        self.thread = None
        self.running = False
        self.on_danmu = on_danmu  # 自定义弹幕处理回调

    def on_message(self, ws, message):
        # 只在出错时输出详细内容，正常弹幕不再 info 打印
        try:
            data = json.loads(message)
        except Exception:
            data = message
        if self.on_danmu:
            try:
                self.on_danmu(data)
            except Exception as e:
                logger.error(f"on_danmu回调异常: {e}\n内容: {message}")

    def on_error(self, ws, error):
        logger.error(f"WebSocket错误: {error}")

    def on_close(self, ws, close_status_code, close_msg):
        logger.info(f"WebSocket关闭: {close_status_code}, {close_msg}")
        self.running = False

    def on_open(self, ws):
        logger.info("WebSocket连接成功")
        self.running = True

    def start(self):
        if self.thread and self.thread.is_alive():
            logger.info("WebSocket接收线程已在运行")
            return
        self.ws = websocket.WebSocketApp(
            self.ws_url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )
        self.thread = threading.Thread(target=self.ws.run_forever, daemon=True)
        self.thread.start()
        logger.info("WebSocket接收线程已启动")

    def stop(self):
        if self.ws:
            self.ws.close()
        self.running = False
        logger.info("WebSocket接收线程已停止")

# 全局实例
huahua_ws_receiver = None

def auto_start_huahua_ws_receiver():
    global huahua_ws_receiver
    config = get_config()
    enable = config.get('huahua', {}).get('danmu_receive_enable', False)
    if enable:
        if huahua_ws_receiver is None:
            huahua_ws_receiver = HuahuaWSReceiver()
        huahua_ws_receiver.start()
    else:
        if huahua_ws_receiver and huahua_ws_receiver.running:
            huahua_ws_receiver.stop()
            huahua_ws_receiver = None

# 可在主程序入口调用 auto_start_huahua_ws_receiver()
if __name__ == "__main__":
    auto_start_huahua_ws_receiver()
    input("按回车键退出...\n")
    if huahua_ws_receiver:
        huahua_ws_receiver.stop()
